package com.ljt.yupictureddd.infrastracture.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.ljt.yupictureddd.infrastracture.config.CosClientConfig;
import com.ljt.yupictureddd.infrastracture.api.CosManager;
import com.ljt.yupictureddd.infrastracture.manager.upload.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;


@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    CosClientConfig cosClientConfig;

    @Resource
    CosManager cosManager;


    /**
     * 上传图片
     *
     * @param inputSource
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // TODO
        // 1.校验图片
        validatePicture(inputSource);
        // 2.拼出图片上传地址
        String uuid = RandomUtil.randomString(16);
        // TODO
        String originalFilename = getOriginalFilename(inputSource);// String originalFilename = inputSource.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        // 3.创建临时文件，然后上传并解析结果，再封装返回（这里直接复制FileController上传文件代码）
        File tempFile = null;
        try {
            tempFile = File.createTempFile(uploadPath, "");
            // TODO 处理文件来源
            processFile(inputSource, tempFile);// inputSource.transferTo(tempFile);
            // 3.1上传图片文件后，调用了智能万象，就可可以直接拿到Result,拿到CiUploadResult
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);
            // 3.2Result一直一直拿，就可以那个腾讯云智能万象分析出的图片详情了（一定要打开腾讯云的智能万象，这个叫CiUploadResult）
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 获得压缩为webp的的结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> processResultsObjectList = processResults.getObjectList();// 我们这里是先格式转换webp，再缩放成缩略图
            if (CollUtil.isNotEmpty(processResultsObjectList)) {
                // 封装压缩图，把他压缩图封装到返回结果
                CIObject compressedCiObject = processResultsObjectList.get(0);
                // 缩略图默认就等于压缩图，这样才是正常的逻辑，有了缩略图就用缩略图,防止页面展示不出缩略图
                CIObject thumbnailCiObject = compressedCiObject;
                if (processResultsObjectList.size() >= 1) {
                    // 还有要保存缩略图，封装到返回结果
                    thumbnailCiObject = processResultsObjectList.get(1);
                }
                return buildUploadPictureResult(compressedCiObject, thumbnailCiObject, originalFilename,imageInfo);

            }
            return buildUploadPictureResult(imageInfo, uploadPath, originalFilename, tempFile);
        } catch (Exception e) {
            log.error("图片上传到文件存储失败", e);
            throw new RuntimeException(e);
        } finally {
            // 4.最后一定要删除临时文件
            this.deleteTempFile(tempFile, uploadPath);
        }
    }

    /**
     * 封装返回结果
     *
     * @param compressedCiObject
     * @param thumbnailCiObject
     * @param originalFilename
     * @return
     */
    private UploadPictureResult buildUploadPictureResult(CIObject compressedCiObject, CIObject thumbnailCiObject, String originalFilename,ImageInfo imageInfo) {
        int width = compressedCiObject.getWidth();
        int height = compressedCiObject.getHeight();
//            计算宽高比
        double picScale = NumberUtil.round(width / 1.0 / height, 2).doubleValue();
//            填入数据去
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        // 设置压缩后的原图地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(Long.valueOf(compressedCiObject.getSize()));
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 设置缩略图
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
//            返回可以访问的地址
        return uploadPictureResult;
    }

    /**
     * 生成本地临时文件
     *
     * @param inputSource
     * @param tempFile
     */
    protected abstract void processFile(Object inputSource, File tempFile);

    /**
     * 得到文件名字
     *
     * @param inputSource
     * @return
     */
    protected abstract String getOriginalFilename(Object inputSource);

    /**
     * 校验文件
     *
     * @param inputSource
     */
    protected abstract void validatePicture(Object inputSource);

    /**
     * 删除临时文件
     *
     * @param tempFile
     * @param uploadPath
     */
    private void deleteTempFile(File tempFile, String uploadPath) {
        boolean delete = tempFile.delete();
        if (!delete) {
            log.error("file delete error, filepath = {}", uploadPath);
        }
    }

    /**
     * 封装返回结果
     */
    private UploadPictureResult buildUploadPictureResult(ImageInfo imageInfo, String uploadPath, String originalFilename, File tempFile) {
        int width = imageInfo.getWidth();
        int height = imageInfo.getHeight();
//            计算宽高比
        double picScale = NumberUtil.round(width / 1.0 / height, 2).doubleValue();
//            填入数据去
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(tempFile));
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
//            返回可以访问的地址
        return uploadPictureResult;
    }


}
